﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using cma.cimiss.client;
using cma.cimiss;
using System.IO;
using System.Diagnostics;
using System.Threading;
namespace xzjxhybJY
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private delegate void UpdateProgressBarDelegate(System.Windows.DependencyProperty dp, Object value);
        string IP = "172.18.142.167", pwd = "qxtuser1", useName = "qxtuser";
        CalendarDateRange dr1 = new CalendarDateRange((DateTime.Now.Date).AddDays(+1), DateTime.MaxValue), dr2 = new CalendarDateRange((DateTime.Now.Date).AddDays(+1), DateTime.MaxValue);
        public MainWindow()
        {
            InitializeComponent();
            SC.SelectedIndex=1;
            sDate.BlackoutDates.Add(new CalendarDateRange((DateTime.Now.Date).AddDays(+1), DateTime.MaxValue));
            eDate.BlackoutDates.Add(dr2);
            progressBar1.Maximum = 100;


        }

        private void sDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            eDate.BlackoutDates.Remove(dr1);
            dr1 = new CalendarDateRange(new DateTime(), Convert.ToDateTime(sDate.Text).AddDays(-1));
            eDate.SelectedDate = null;
            eDate.BlackoutDates.Add(dr1);

        }
        public void Save(string strDate, string strTime)
        {           
            string strError = "";
            string strSK = "";
            int rst1 = 0, rst2 = 0;

            string strSKPath = @"\\" + IP + @"\气象台\天气预报\乡镇精细化预报\实况";
            string strLS = strSKPath + "\\" + strDate.Substring(0, 4);
            if (!Directory.Exists(strLS))
            {
                Directory.CreateDirectory(strLS);
            }
            strLS += "\\" + strDate.Substring(4, 2);
            if (!Directory.Exists(strLS))
            {
                Directory.CreateDirectory(strLS);
            }
            string strFile = strLS + "\\" + strDate + strTime + "实况.txt";
            if((!File.Exists(strFile))||(FGSK.IsChecked == true))
            {
                HQSK classHQSK = new HQSK();
                string strQXSK = classHQSK.CIMISSHQQXSK(strDate, strTime, ref rst1, ref strError);
                string strSZSK = classHQSK.CIMISSHQXZSK(strDate, strTime, ref rst2, ref strError);
                if ((rst1 == 0) && (rst2 == 0))//如果CIMISS返回均为0
                {
                    //将前一天20至当天20的实况数据保存至\\IP\气象台\天气预报\乡镇精细化预报\实况\年\月 文件夹下
                    strSK = strQXSK + '\n' + strSZSK;
                    errorBox.Text = strError;
                    FileStream myFs = new FileStream(strFile, FileMode.Create);
                    StreamWriter mySw = new StreamWriter(myFs, Encoding.Default);
                    mySw.Write(strSK);
                    mySw.Close();
                    myFs.Close();
                }
            }
                          
                
                

            if (strError.Length == 0)
                {
                    errorBox.Text = "无异常";
                }
            else
            {
                MessageBox.Show("CIMISS出错，返回代码为：" + strError);
            }
        }
            


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            double douLS;
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressBar1.SetValue);
            UpdateProgressBarDelegate updateText = new UpdateProgressBarDelegate(txtboxJD.SetValue);
            if ((!(sDate.SelectedDate.ToString().Length==0))&& (!(eDate.SelectedDate.ToString().Length == 0)))
            {
                //连接共享文件夹
                Process process = new Process();
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.CreateNoWindow = true;
                process.Start();
                process.StandardInput.WriteLine("net use  \\\\" + IP + "\\ipc$ " + pwd + " /user:" + useName + "");//连接共享文件夹
                Thread.Sleep(1000);
                string strSC = SC.SelectedItem.ToString();
                DateTime dateStartDate = Convert.ToDateTime(sDate.SelectedDate), dateEndDate = Convert.ToDateTime(eDate.SelectedDate);
                DateTime dateLS = dateStartDate,dateLS2=dateLS;
                int intLS = 0;
                for (int i = 0; DateTime.Compare(dateLS2, dateEndDate) <= 0; i++)
                {
                    intLS++;
                    dateLS2 = dateLS2.AddDays(1);
                }
                for (int i = 0;DateTime.Compare(dateLS,dateEndDate)<=0;i++)
                {
                    douLS = (i+1)*100/intLS;
                    string strDate = dateLS.ToString("yyyyMMdd");
                    Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, Math.Ceiling(douLS) });
                    Dispatcher.Invoke(updateText, System.Windows.Threading.DispatcherPriority.Background, new object[] { TextBox.TextProperty, strDate });
                    Save(strDate, SC.Text);
                    dateLS = dateLS.AddDays(1);

                }
                

                /*断开连接*/
                process.StandardInput.WriteLine("net use  \\\\" + IP + "\\ipc$ /del");
                Dispatcher.Invoke(updateText, System.Windows.Threading.DispatcherPriority.Background, new object[] { TextBox.TextProperty, "完成" });
            }
            else
            {
                MessageBox.Show("请选择起止时间");
            }
            
            
        }
    }

    public class  HQSK
    {
        string configpathPath = System.Environment.CurrentDirectory + @"\设置文件\路径设置.txt";
        string configXZPath = System.Environment.CurrentDirectory + @"\设置文件\旗县乡镇.txt";

        public string CIMISSHQQXSK(string strDate, string strTime,ref int rst1, ref string strError)
        {
            
            /* 1. 定义client对象 */
            DataQueryClient client = new DataQueryClient();

            /* 2.   调用方法的参数定义，并赋值 */
            /*   2.1 用户名&密码 */
            String userId = "BEHT_BFHT_2131";// 
            String pwd = "YZHHGDJM";// 
            /*   2.2 接口ID */
            String interfaceId1 = "getSurfEleByTimeAndStaID";
            /*   2.3 接口参数，多个参数间无顺序 */
            Dictionary<String, String> paramsqx = new Dictionary<String, String>();
            // 必选参数
            paramsqx.Add("dataCode", "SURF_CHN_MUL_HOR"); // 资料代码
                                                          //检索时间段
            string strToday = strDate + strTime + "0000";
            string strLS = DateTime.ParseExact(strToday, "yyyyMMddHHmmss", null).ToString("yyyy-MM-dd HH:mm:ss");
            strToday = Convert.ToDateTime(strLS).ToUniversalTime().ToString("yyyyMMddHH0000");//ToUniversalTime将时间转换为UTC
            paramsqx.Add("times", strToday);

            /*以下程序功能为：根据设置文件夹下的旗县乡镇设置文件获取CIMISS查询需要配置的台站号*/
            StreamReader sr = new StreamReader(configXZPath, Encoding.Default);
            String line;
            //读取设置文件的旗县乡镇文件中第一行，确认旗县镇数
            line = sr.ReadLine();
            sr.Close();
            string[] linShi1 = line.Split(':');
            int intQXGS = Convert.ToInt16(linShi1[1]);
            string QXID = "";

            //每两行第一列为旗县ID
            int lineCount = 0;
            sr = new StreamReader(configXZPath, Encoding.Default);
            while (lineCount < intQXGS * 2 + 1)
            {
                line = sr.ReadLine();
                if ((lineCount > 1) && (lineCount % 2 == 0))
                {
                    QXID += line.Split(',')[0] + ',';
                }
                lineCount++;

            }
            sr.Close();
            QXID = QXID.Substring(0, QXID.Length - 1);

            paramsqx.Add("staIds", QXID);//选择区站号，该处后面调整，从乡镇名单中获取
            paramsqx.Add("elements", "Station_Name,Cnty,Station_Id_C,TEM_Max_24h,TEM_Min_24h,PRE_24h");// 检索要素：站号、站名、过去24h最高、最低气温、24小时降水量
            // 可选参数
            //paramsqx.Add("orderby", "Station_ID_C:ASC"); // 排序：按照站号从小到大
            /*   2.4 返回文件的格式 */
            String dataFormat = "Text";
            StringBuilder QXSK = new StringBuilder();//返回字符串
            // 初始化接口服务连接资源
            client.initResources();
            // 调用接口
            int rst = client.callAPI_to_serializedStr(userId, pwd, interfaceId1, paramsqx, dataFormat, QXSK);
            // 释放接口服务连接资源
            client.destroyResources();
            string strData = Convert.ToString(QXSK);
             strLS = strData.Split('"')[1];
            rst = Convert.ToInt32(strLS);
            rst1 = rst;
            
            if (rst == 0)
            {
                string[] SZlinshi = strData.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                strData = "";
                /*删掉CIMISS返回数据第一行的返回信息以及第二行的列标题，只保留数据*/
                for (int i = 0; i < SZlinshi.Length; i++)
                {
                    if (i > 1)
                    {
                        strData += SZlinshi[i] + '\n';
                    }
                }
                strData = strData.Substring(0, strData.Length - 1);
                //对旗县实况排序，使得旗县的顺序与旗县名单文件中的一致，便于程序后续处理
                lineCount = 0;
                strLS = strData;
                strData = "";
                sr = new StreamReader(configXZPath, Encoding.Default);
                while (lineCount < intQXGS * 2 + 1)
                {
                    line = sr.ReadLine();
                    if ((lineCount > 1) && (lineCount % 2 == 0))
                    {
                        QXID = line.Split(',')[0];
                        SZlinshi = strLS.Split('\n');
                        for (int j = 0; j < SZlinshi.Length; j++)
                        {
                            if (SZlinshi[j].Contains(QXID))//判断该行是否存在该旗县区站号，如果包含，就把整行数据保存
                            {
                                strData += SZlinshi[j] + "\n";
                            }
                        }
                    }
                    lineCount++;

                }
                sr.Close();
                strData = strData.Substring(0, strData.Length - 1);
            }
            else
            {
                strError += strData+'\n';
            }
           
            return strData;

        }
        public string CIMISSHQXZSK(string strDate,string strTime, ref int rst2,ref string strError)//函数输入为查询实况的日期与时次，输出为旗县实况与返回CIMISS错误代码；
        {
            string strData = "";

            /* 1. 定义client对象 */
            DataQueryClient client = new DataQueryClient();

            /* 2.   调用方法的参数定义，并赋值 */
            /*   2.1 用户名&密码 */
            String userId = "BEHT_BFHT_2131";// 
            String pwd = "YZHHGDJM";// 
            /*   2.2 接口ID */
            String interfaceId1 = "statSurfEleByStaID";
            /*   2.3 接口参数，多个参数间无顺序 */
            Dictionary<String, String> paramsqx = new Dictionary<String, String>();
            // 必选参数
            paramsqx.Add("dataCode", "SURF_CHN_MUL_HOR"); // 资料代码
            //检索时间段
            string strToday = strDate + strTime + "0000";
            string strLS;
            strLS = DateTime.ParseExact(strToday, "yyyyMMddHHmmss", null).ToString("yyyy-MM-dd HH:mm:ss");
            strToday = Convert.ToDateTime(strLS).ToUniversalTime().ToString("yyyyMMddHH0000");//ToUniversalTime将时间转换为UTC
            string stYesterday = Convert.ToDateTime(strLS).AddDays(-1).ToUniversalTime().ToString("yyyyMMddHH0000");
            string timeRange1 = "(" + stYesterday + "," + strToday + "]";
            paramsqx.Add("timeRange", timeRange1);

            /*以下程序功能为：根据设置文件夹下的旗县乡镇设置文件获取CIMISS查询需要配置的台站号*/
            StreamReader sr = new StreamReader(configXZPath, Encoding.Default);
            String line;
            //读取设置文件的旗县乡镇文件中第一行，确认旗县个数
            line = sr.ReadLine();
            sr.Close();
            string[] linShi1 = line.Split(':');
            int intQXGS = Convert.ToInt16(linShi1[1]);
            string XZID = "";
            //每两行第一列为旗县ID 
            int lineCount = 0;
            sr = new StreamReader(configXZPath, Encoding.Default);
            while (lineCount < intQXGS * 2 + 1)
            {
                line = sr.ReadLine();
                if ((lineCount > 1) && (lineCount % 2 == 0))//避免取到第一行的旗县个数，因此lineCount>1，站号为编号偶数行故对2取余
                {
                    for (int i = 1; i < line.Split(',').Length; i++)//提取乡镇区站号，编号为0是旗县站号，故从1开始
                    {
                        XZID += line.Split(',')[i] + ',';
                    }

                }
                lineCount++;

            }
            sr.Close();
            XZID = XZID.Substring(0, XZID.Length - 1);

            paramsqx.Add("staIds", XZID);//选择区站号，从乡镇名单中获取
            paramsqx.Add("elements", "Station_Name,Cnty,Station_Id_C");// 检索要素：站号、旗县、区站号
            paramsqx.Add("statEles", "MAX_TEM_Max,MIN_TEM_MIN,SUM_PRE_1h");// 统计要素最高温度的最大值，与最低温度的最小值以及小时降水量
            // 可选参数
            paramsqx.Add("orderby", "Station_ID_C:ASC"); // 排序：按照站号从小到大
            /*   2.4 返回文件的格式 */
            String dataFormat = "Text";
            StringBuilder retStrXZ = new StringBuilder();//返回字符串
            // 初始化接口服务连接资源
            client.initResources();
            // 调用接口
            int rst = client.callAPI_to_serializedStr(userId, pwd, interfaceId1, paramsqx, dataFormat, retStrXZ);
            // 释放接口服务连接资源
            client.destroyResources();
            strData = Convert.ToString(retStrXZ);
            strLS = strData.Split('"')[1];
            rst = Convert.ToInt32(strLS);
            rst2 = rst;
            if (rst==0)
            {
                string[] SZlinshi = strData.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                strData = "";
                /*删掉CIMISS返回数据第一行的返回信息以及第二行的列标题，只保留数据*/
                for (int i = 0; i < SZlinshi.Length; i++)
                {
                    if (i > 1)
                    {
                        strData += SZlinshi[i] + "\n";
                    }
                }
                strData = strData.Substring(0, strData.Length - 1);
            }
            else
            {
                strError += strData;
            }
            

           

            return strData;

        }


    }

}
